#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<linux/stat.h>
#include<string.h>

int main()
{
	char buf1[1024];
	char buf[1024];
	int pid,f,flag,fd1,fd2,pfd;

	unlink("fifoa1");
	unlink("fifob2");
	unlink("pfifo");
	mkfifo("fifoa1",0666);
	mkfifo("fifob2",0666);
	mkfifo("pfifo",0666);

	pid=fork();
	if(pid>0)
	{
		pfd=open("pfifo",O_RDONLY);
		while((f=read(pfd,buf,sizeof(buf)))>0)
			printf("%s",buf);
		close(pfd);
		printf("pfd closed!\n");
	}
	else if(pid==0)
	{
		// 首先给管道里面写入初始化的数据"00000\n"
		if((fd1=open("fifoa1",O_WRONLY)) == -1){
			printf("Error!\n");
		}
		if((fd2=open("fifob2",O_WRONLY)) == -1){
			printf("Error!\n");
		}
		strcpy(buf1, "00000\n");
		write(fd1,buf1,sizeof(buf1));
		write(fd2,buf1,sizeof(buf1));
		close(fd1);
		close(fd2);
		usleep(100000);

		// 下面由服务器循环将数据写入客户端
		while(1)
		{
			fd1=open("fifoa1",O_WRONLY);
			fd2=open("fifob2",O_WRONLY);
			printf("\nplease change you sent to client id [0/1/2]: \n" );
			scanf("%d",&flag);
			getchar();		// 回收换行符
			if(flag==0)
			{
				printf("you sent to all client!\n");
				printf("Please input message: ");
				fgets(buf1,sizeof(buf1),stdin);
				write(fd1,buf1,sizeof(buf1));
				write(fd2,buf1,sizeof(buf1));
			}
			else if(flag==1)
			{
				printf("you sent to client1!\n");
				printf("Please input message: ");
				fgets(buf1,sizeof(buf1),stdin);
				write(fd1,buf1,sizeof(buf1));
			}
			else if(flag==2)
			{
				printf("you sent to client2!\n");
				printf("Please input message: ");
				fgets(buf1,sizeof(buf1),stdin);
				write(fd2,buf1,sizeof(buf1));
			}
			close(fd1);
			close(fd2);
			usleep(100000);
		}
	}
	return 0;
}

